package com.zzz.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzz.common.core.constants.Constants;
import com.zzz.common.core.domain.TableDataInfo;
import com.zzz.common.core.enums.ResultCode;
import com.zzz.common.core.utils.ThreadLocalUtil;
import com.zzz.common.security.exception.ServiceException;
import com.zzz.common.security.service.TokenService;
import com.zzz.friend.domain.exam.Exam;
import com.zzz.friend.domain.exam.dto.ExamDTO;
import com.zzz.friend.domain.exam.dto.ExamQueryDTO;
import com.zzz.friend.domain.exam.vo.ExamVO;
import com.zzz.friend.domain.user.UserExam;
import com.zzz.friend.manager.ExamCacheManager;
import com.zzz.friend.mapper.exam.ExamMapper;
import com.zzz.friend.mapper.exam.UserExamMapper;
import com.zzz.friend.service.user.UserExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.friend.service.exam.impl
 * @Author: zhai
 * @CreateTime: 2025-11-05  18:40
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class UserExamServiceImpl implements UserExamService {

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * @description: 报名竞赛
     * @author: zhai
     * @date: 2025/11/5 18:43
     * @param:
     * @return:
     **/
    @Override
    public int enter(String token, Long examId) {
        log.info("用户报名竞赛开始");
//        Long userId = tokenService.getUserId(token, secret);
//        if (userId == null) {
//            log.error("token错误");
//            throw new ServiceException(ResultCode.FAILED_TOKEN_ERROR);
//        }
        // 从线程中拿取
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            log.error("当前线程存储的用户不存在");
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 校验竞赛
        Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>().eq(Exam::getExamId, examId));
        if (exam == null) {
            log.error("竞赛不存在,不能报名");
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        if (exam.getEndTime().isAfter(LocalDateTime.now())) {
            log.error("竞赛已经结束,不能报名");
            throw new ServiceException(ResultCode.EXAM_IS_FINISH);
        }
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if (userExam != null) {
            log.error("用户已经报名该竞赛");
            throw new ServiceException(ResultCode.USER_EXAM_EXISTS);
        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            log.error("竞赛已经开始,不能报名");
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        examCacheManager.addUserExamCache(userId, examId);
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    /**
     * @description: 获取用户报的竞赛列表
     * @author: zhai
     * @date: 2025/11/5 21:36
     * @param: [examQueryDTO]
     * @return: com.zzz.common.core.domain.TableDataInfo
     **/
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 先查缓存（u:e:l:用户id）,如果缓存中能拿到就从缓存中拿
        // 如果查询不到就从数据库中查询
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = examCacheManager.getExamListSize(examQueryDTO.getType(), userId);
        List<ExamVO> examVOList;
        if (total == 0 || total == null) {
            log.info("缓存中没有数据，从数据库中获取数据");
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            // 刷新缓存
            examCacheManager.refreshCache(examQueryDTO.getType(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            log.info("缓存中有数据");
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getExamListSize(examQueryDTO.getType(),  userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }


}
